class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> st;
        heights.insert(heights.begin(),0);
        heights.push_back(0);
        int maxArea=0;

        for (int i=0;i<heights.size();++i){
            while (!st.empty()&&heights[i]<heights[st.top()]){
                int currIdx=st.top();
                st.pop();
                int width=i-st.top()-1;
                int area=heights[currIdx]*width;
                maxArea=max(maxArea,area);
            }
            st.push(i);
        }
        return maxArea;
    }
};